package models

import (
	"fmt"
	"go_test/config"
	"gorm.io/gorm"
	"math/rand"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"
)

type IosDevice struct {
	Id            int    `json:"id" gorm:"primaryKey"`
	Name          string `json:"name"`
	Version       string `json:"version"`
	Model         string `json:"model"`
	SafariVersion string `json:"safariVersion"`
}

func (IosDevice) TableName() string {
	return "ios_device"
}

func (d IosDevice) BuildUa() string {
	osVersion := strings.ReplaceAll(d.Version, ".", "_")
	return fmt.Sprintf("Mozilla/5.0 (iPhone; CPU iPhone OS %s like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/%s Mobile/15E148 Safari/604.1",
		osVersion, d.SafariVersion)
}

var (
	iosDevicesAll  []IosDevice
	iosDevicesHigh []IosDevice // >= 14.5
	iosDevicesLow  []IosDevice // < 14.5
	iosInitOnce    sync.Once
)

// 比较版本号（简单支持 x.y.z）
func versionCompare(a, b string) int {
	aParts := strings.Split(a, ".")
	bParts := strings.Split(b, ".")

	for i := 0; i < len(aParts) && i < len(bParts); i++ {
		aNum, _ := strconv.Atoi(aParts[i])
		bNum, _ := strconv.Atoi(bParts[i])
		if aNum > bNum {
			return 1
		} else if aNum < bNum {
			return -1
		}
	}
	if len(aParts) > len(bParts) {
		return 1
	} else if len(aParts) < len(bParts) {
		return -1
	}
	return 0
}

// 初始化方法（在程序启动时调用）
func InitIosDevices() {
	iosInitOnce.Do(func() {
		db := config.DB

		err := db.Find(&iosDevicesAll).Error
		if err != nil && err != gorm.ErrRecordNotFound {
			panic(fmt.Sprintf("加载 ios_device 数据失败: %v", err))
		}

		if len(iosDevicesAll) == 0 {
			panic("ios_device 表中无数据")
		}

		// 排序所有设备，确保版本有序
		sort.Slice(iosDevicesAll, func(i, j int) bool {
			return versionCompare(iosDevicesAll[i].Version, iosDevicesAll[j].Version) < 0
		})

		// 分类
		splitVersion := "14.5"
		for _, device := range iosDevicesAll {
			if versionCompare(device.Version, splitVersion) >= 0 {
				iosDevicesHigh = append(iosDevicesHigh, device)
			} else {
				iosDevicesLow = append(iosDevicesLow, device)
			}
		}
	})
}

// 获取任意一个设备
func GetRandomIosDevice() IosDevice {
	if len(iosDevicesAll) == 0 {
		panic("ios_device 数据为空，请先调用 InitIosDevices()")
	}
	rand.Seed(time.Now().UnixNano())
	return iosDevicesAll[rand.Intn(len(iosDevicesAll))]
}

// 获取高版本设备
func GetRandomIosDeviceHigh() IosDevice {
	if len(iosDevicesHigh) == 0 {
		panic("没有符合条件的高版本 ios_device 设备，请先调用 InitIosDevices()")
	}
	rand.Seed(time.Now().UnixNano())
	return iosDevicesHigh[rand.Intn(len(iosDevicesHigh))]
}

// 获取低版本设备
func GetRandomIosDeviceLow() IosDevice {
	if len(iosDevicesLow) == 0 {
		panic("没有符合条件的低版本 ios_device 设备，请先调用 InitIosDevices()")
	}
	rand.Seed(time.Now().UnixNano())
	return iosDevicesLow[rand.Intn(len(iosDevicesLow))]
}
